let url = require ('url');
let useragent = require ('useragent');
module.exports.getData = function ( req )
{
    let requestedUrl = url.parse (req.originalUrl);
    let startTime = new Date ();
    // Our format argument above contains key-value pairs for the output
    // object we send to Winston. Let's use this to format our results:
    let data = {};
    let userAgent = useragent.parse (req.headers[ 'user-agent' ]).toString ();
    userAgent = (userAgent != "Other 0.0.0 / Other 0.0.0" ) ? userAgent : req.headers[ 'user-agent' ];
    let weixin = req.weixin ? JSON.stringify (req.weixin) : "-";
    // let request = JSON.stringify(req);
    let tokens = {
        ':method': req.method,
        ':date': startTime.format ('yyyy-MM-dd HH:mm:ss'),
        // ':statusCode': _colorStatus(res.statusCode),
        ':responseTime': (new Date () - startTime) + ' ms',
        ':url\\[([a-z]+)\\]': function ( str, segment )
        {
            return requestedUrl[ segment ];
        },
        ':ip': req.headers[ 'x-forwarded-for' ] || req.ip || req.connection.remoteAddress,
        ':userAgent': userAgent
    };
    // Let's define a default format
    if (typeof(format) !== 'object')
    {
        format = {
            method       : ':method',
            date         : ':date',
            // status: ':statusCode',
            url          : ':url[pathname]',
            response_time: ':responseTime',
            user_agent   : ':userAgent'
        };
    }
    // ... and replace our tokens!
    let token = '';
    let replaceToken = function ( str, match )
    {
        return tokens[ token ];
    };
    for (let key in format)
    {
        data[ key ] = format[ key ];
        for ( token in tokens)
        {
            data[ key ] = data[ key ].replace (new RegExp (token), typeof(tokens[ token ]) === 'function' ? tokens[ token ] : replaceToken);
        }
    }
    return data;
};